<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElButton, ElInput, ElForm, ElFormItem, ElDialog, ElSelect, ElOption, ElPagination } from 'element-plus';

// 线索数据
const clueData = ref([]);

// 搜索条件
const searchForm = reactive({
  clueId: '',
  phone: '',
  source: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框状态
const dialogVisible = ref(false);
// 编辑模式
const editMode = ref(false);
// 当前编辑的线索ID
const currentClueId = ref(null);
// 表单数据
const formData = reactive({
  clueId: '',
  name: '',
  phone: '',
  gender: '',
  age: '',
  activityInfo: '',
  source: ''
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '姓名长度在1到50个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  age: [
    { pattern: /^\d+$/, message: '请输入有效的年龄', trigger: 'blur' }
  ]
};

// 表单引用
const clueFormRef = ref(null);

// 加载线索数据
const loadClueData = () => {
  // 模拟API请求，使用静态数据
  clueData.value = [
    {
      id: 1,
      clueId: '1',
      phone: '14700000001',
      name: '张思',
      gender: '男',
      age: 23,
      activityInfo: '推广介绍',
      createTime: '2025-09-24 17:13:50',
      updateTime: '2025-10-16 10:47:03'
    },
    {
      id: 2,
      clueId: '3',
      phone: '13909129913',
      name: '李迪',
      gender: '男',
      age: 22,
      activityInfo: '推广介绍',
      createTime: '2025-09-28 11:54:02',
      updateTime: '2025-10-16 10:31:08'
    },
    {
      id: 3,
      clueId: '10',
      phone: '1339889002',
      name: '张伟',
      gender: '男',
      age: 22,
      activityInfo: '线上活动',
      createTime: '2025-06-16 13:51:22',
      updateTime: '2025-10-16 10:30:54'
    }
  ];
};

// 计算总数
const total = computed(() => clueData.value.length);

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + Number(pageSize.value);
  return clueData.value.slice(start, end);
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
};

// 处理分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 打开添加对话框
const openAddDialog = () => {
  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  editMode.value = true;
  currentClueId.value = row.id;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除线索
const deleteClue = (row) => {
  ElMessageBox.confirm('确定要删除该线索吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = clueData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      clueData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 保存线索
const saveClue = () => {
  clueFormRef.value.validate((valid) => {
    if (valid) {
      const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      
      if (editMode.value) {
        // 编辑模式
        const index = clueData.value.findIndex(item => item.id === currentClueId.value);
        if (index !== -1) {
          Object.assign(clueData.value[index], formData, { updateTime: now });
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加模式
        const newClue = {
          id: Date.now(), // 模拟生成唯一ID
          clueId: String(clueData.value.length + 1),
          ...formData,
          createTime: now,
          updateTime: now
        };
        clueData.value.push(newClue);
        ElMessage.success('添加成功');
      }
      dialogVisible.value = false;
      resetForm();
    }
  });
};

// 重置表单
const resetForm = () => {
  if (clueFormRef.value) {
    clueFormRef.value.resetFields();
  }
  Object.keys(formData).forEach(key => {
    formData[key] = '';
  });
  currentClueId.value = null;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 组件挂载时加载数据
onMounted(() => {
  loadClueData();
});
</script>

<template>
  <div class="clue-container">
    <div class="search-bar">
      <div class="search-item">
        <label>线索ID</label>
        <ElInput v-model="searchForm.clueId" placeholder="请输入" style="width: 150px;"></ElInput>
      </div>
      <div class="search-item">
        <label>手机号</label>
        <ElInput v-model="searchForm.phone" placeholder="请输入" style="width: 150px;"></ElInput>
      </div>
      <div class="search-item">
        <label>渠道来源</label>
        <ElSelect v-model="searchForm.source" placeholder="请选择" style="width: 150px;">
          <ElOption label="推广介绍" value="推广介绍"></ElOption>
          <ElOption label="线上活动" value="线上活动"></ElOption>
        </ElSelect>
      </div>
      <ElButton type="primary" @click="handleSearch">搜索</ElButton>
      <ElButton @click="handleReset">重置</ElButton>
    </div>
    
    <div class="clue-content">
      <ElTable 
        v-if="clueData.length > 0"
        :data="currentPageData" 
        style="width: 100%;"
        stripe
        border
        fit
      >
        <ElTableColumn 
          prop="clueId" 
          label="线索ID" 
          min-width="80"
        />
        <ElTableColumn 
          prop="phone" 
          label="手机号" 
          min-width="120"
        />
        <ElTableColumn 
          prop="name" 
          label="客户姓名" 
          min-width="100"
        />
        <ElTableColumn 
          prop="gender" 
          label="性别" 
          min-width="80"
        />
        <ElTableColumn 
          prop="age" 
          label="年龄" 
          min-width="80"
        />
        <ElTableColumn 
          prop="activityInfo" 
          label="活动信息" 
          min-width="120"
        />
        <ElTableColumn 
          prop="createTime" 
          label="创建时间" 
          min-width="180"
        />
        <ElTableColumn 
          prop="updateTime" 
          label="更新时间" 
          min-width="180"
        />
        <ElTableColumn 
          label="操作" 
          min-width="120" 
          fixed="right"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <ElButton 
                type="text" 
                @click="openEditDialog(row)"
                size="small" 
                style="color: #409EFF;"
              >
                修改
              </ElButton>
              <ElButton 
                type="text" 
                @click="deleteClue(row)"
                size="small" 
                style="color: #F56C6C;"
              >
                删除
              </ElButton>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-else class="empty-data">暂无线索数据</div>
      
      <!-- 分页组件 -->
      <div class="pagination">
        <span class="total">共 {{ total }} 条</span>
        <ElSelect v-model="pageSize" @change="handleSizeChange" style="width: 100px;">
          <ElOption label="10条/页" value="10"></ElOption>
          <ElOption label="20条/页" value="20"></ElOption>
          <ElOption label="50条/页" value="50"></ElOption>
        </ElSelect>
        <ElPagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          layout="prev, pager, next, jumper"
        ></ElPagination>
      </div>
    </div>
    
    <!-- 添加/编辑线索对话框 -->
    <ElDialog
      :title="editMode ? '编辑线索' : '新增线索'"
      v-model="dialogVisible"
      width="500px"
      @close="closeDialog"
    >
      <ElForm
        ref="clueFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <ElFormItem label="客户姓名" prop="name">
          <ElInput v-model="formData.name" placeholder="请输入客户姓名" />
        </ElFormItem>
        <ElFormItem label="手机号" prop="phone">
          <ElInput v-model="formData.phone" placeholder="请输入手机号" />
        </ElFormItem>
        <ElFormItem label="性别">
          <ElSelect v-model="formData.gender" placeholder="请选择">
            <ElOption label="男" value="男"></ElOption>
            <ElOption label="女" value="女"></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="年龄" prop="age">
          <ElInput v-model.number="formData.age" placeholder="请输入年龄" type="number" />
        </ElFormItem>
        <ElFormItem label="活动信息">
          <ElInput v-model="formData.activityInfo" placeholder="请输入活动信息" />
        </ElFormItem>
        <ElFormItem label="渠道来源">
          <ElSelect v-model="formData.source" placeholder="请选择">
            <ElOption label="推广介绍" value="推广介绍"></ElOption>
            <ElOption label="线上活动" value="线上活动"></ElOption>
          </ElSelect>
        </ElFormItem>
      </ElForm>
      
      <template #footer>
        <ElButton @click="closeDialog">取消</ElButton>
        <ElButton type="primary" @click="saveClue">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
/* 确保body没有默认margin */
:global(body) {
  margin: 0;
  padding: 0;
}

.lead-container {
  padding: 15px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

/* 搜索栏样式 */
.search-bar {
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  white-space: nowrap;
  font-weight: 500;
  color: #606266;
}

.lead-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 15px;
}

.lead-content {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.empty-data {
  text-align: center;
  padding: 100px 0;
  color: #999;
  font-size: 16px;
}

/* 自定义表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
}

:deep(.el-table__header th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
  padding: 15px 0;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-table__row) {
  height: 60px;
}

:deep(.el-button--small) {
  padding: 8px 16px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  gap: 15px;
  flex-shrink: 0;
}

.pagination .total {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

/* 操作按钮样式 */
:deep(.el-button--text) {
  padding: 8px 10px;
}
</style>